package train.DAY625;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class TcpServer {
    //定义存储socket对象的集合
    public  static Map<String,Socket> clientSockets  = new HashMap<>();
    public static void main(String[] args) throws IOException{
            ServerSocket socket=new ServerSocket(9090);
            while(true) {
                Socket accept = socket.accept();//block
                OutputStream outputStream = accept.getOutputStream();
                clientSockets.put(accept.getRemoteSocketAddress()+"",accept);
               // outputStream.write("hello from server".getBytes());

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            while(true) {
                                //收信息
                                InputStream inputStream = accept.getInputStream();
                                byte[] data = new byte[100];
                                int len = inputStream.read(data);//block
                                String msg = new String(data, 0, len);

                                System.out.println(accept.getRemoteSocketAddress() + "：" +msg);

                                //p2p  todo



                                //广播数据给所有连接的socket
//                                for(Map.Entry  oneSocket:clientSockets.entrySet()){
//
//                                    Socket  socket1 = (Socket) oneSocket.getValue();
//                                    OutputStream os = socket1.getOutputStream();
//
//                                    os.write( (accept.getRemoteSocketAddress()+ ":"+  msg).getBytes());
//                                }

                                //发消息
                                Scanner scanner = new Scanner(System.in);
                                String input = scanner.nextLine();//block
                                outputStream.write( input.getBytes());
                                outputStream.flush();

                                if (msg.equals("quit")){
                                    accept.close();
                                }
                            }
                        }catch (IOException  exp){
                            exp.printStackTrace();
                        }
                    }
                }.start();

            }
    }
}
